<template>
  <div class="template-container">
    <el-card class="template-card">
      <div class="title-wrapper">
        <h2 class="title">合同模板管理</h2>
      </div>

      <!-- 上传区域 -->
      <div class="upload-area">
        <el-upload
          ref="upload"
          class="upload-box"
          drag
          :accept="'.doc,.docx'"
          :limit="1"
          :http-request="customUpload"
          :before-upload="beforeUpload"
          :on-change="handleContractChange"
          :on-error="handleUploadError"
          :on-remove="handleRemove"
          :file-list="fileList"
        >
          <div class="upload-content">
            <i class="el-icon-upload upload-icon" />
            <div class="el-upload__text">
              将文件拖到此处，或<em>点击上传</em>
            </div>
            <div class="upload-tip">只能上传Doc/Docx文件</div>
          </div>
        </el-upload>

        <!-- 已上传文件列表 -->
        <div v-if="fileList.length" class="file-list">
          <div class="file-item">
            <i class="el-icon-document" />
            <span class="file-name">{{ fileList[0].name }}</span>
            <i class="el-icon-circle-close" @click="handleRemove" />
          </div>
        </div>

        <!-- 操作按钮 -->
        <div class="button-group">
          <!-- <el-button type="primary" @click="handleSave" :loading="saveLoading"
            >保存模板</el-button
          > -->
          <el-button
            type="success"
            :loading="downloadLoading"
            @click="handleDownload"
          >下载模板</el-button>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
import { addTemplateApi, selTemplateApi } from '@/api/uploadFile'
import request from '@/utils/requestH2' // 导入配置了拦截器的 axios 实例

export default {
  name: 'TemplateManagement',
  data() {
    return {
      uploadUrl:
        process.env.VUE_APP_BASE_HOME_API + '/basicData/template/addTemplate', // 上传地址
      fileList: [], // 文件列表
      templateUrl: '', // 模板文件URL
      templateId: '1', // 模板ID，这里写死为1，实际应该根据需求获取
      saveLoading: false, // 添加保存按钮loading状态
      downloadLoading: false // 添加下载按钮loading状态
    }
  },
  created() {
    this.selTemplateById()
  },
  methods: {
    // 查询项目模板
    async selTemplateById() {
      const res = await selTemplateApi()
      console.log(res)
      if (res.code === 1) {
        // 如果返回的是文件路径，处理显示名称
        if (res.data && res.data.templateFile) {
          this.fileList = [
            {
              name: this.getFileName(res.data.templateFile), // 使用处理后的文件名
              url: res.data.templateFile // 保存完整URL
            }
          ]
        }
      }
    },

    // 获取格式化的文件名
    getFileName(url) {
      if (!url) return ''
      // 截取_后面的部分作为文件名
      return url.split('_').pop()
    },

    // 文件状态改变时的钩子
    handleContractChange(file, fileList) {
      this.fileList = fileList.slice(-1) // 只保留最新的一个文件
      console.log('当前文件列表:', this.fileList)
    },
    // 上传文件之前的钩子
    beforeUpload(file) {
      const isDocx =
        file.type ===
          'application/vnd.openxmlformats-officedocument.wordprocessingml.document' ||
        file.type === 'application/msword'
      const isLt10M = file.size / 1024 / 1024 < 10

      if (!isDocx) {
        this.$message.error('上传文件只能是 doc/docx 格式!')
        return false
      }
      if (!isLt10M) {
        this.$message.error('上传文件大小不能超过 10MB!')
        return false
      }
      return true
    },

    // 文件上传成功时的钩子
    handleUploadSuccess(response, file, fileList) {
      if (response.code === 1) {
        this.$message.success('上传成功')
        this.templateUrl = response.data // 保存文件URL
        // 更新显示的文件名
        this.fileList = [
          {
            name: this.getFileName(response.data),
            url: response.data
          }
        ]
        console.log('文件上传成功，URL:', this.templateUrl)
      } else {
        this.$message.error(response.msg || '上传失败')
        this.fileList = []
        this.$refs.upload.clearFiles()
      }
    },

    // 文件上传失败时的钩子
    handleUploadError(err) {
      this.$message.error('上传失败: ' + err)
      this.fileList = []
      this.$refs.upload.clearFiles()
      console.error('文件上传失败:', err)
    },

    // 移除文件
    handleRemove() {
      this.fileList = []
      this.templateUrl = '' // 清空文件URL
      console.log('文件已移除')
    },

    // 保存模板
    async handleSave() {
      if (!this.templateUrl) {
        this.$message.warning('请先上传文件')
        return
      }

      this.saveLoading = true
      try {
        const formData = new FormData()
        formData.append('file', this.fileList[0].raw)
        formData.append('url', this.templateUrl)

        const res = await addTemplateApi(formData)
        if (res.code === 1) {
          this.$message.success('保存成功')
          // 可以在这里清空文件列表
          this.handleRemove()
        } else {
          this.$message.error(res.msg || '保存失败')
        }
      } catch (error) {
        console.error('保存失败:', error)
        this.$message.error('保存失败，请重试')
      } finally {
        this.saveLoading = false
      }
    },

    // 下载模板
    async handleDownload() {
      try {
        this.downloadLoading = true

        // 检查是否有文件可下载
        if (!this.fileList.length || !this.fileList[0].url) {
          this.$message.warning('文件链接不存在')
          return
        }

        const url = this.fileList[0].url
        // 拼接完整的下载地址
        const baseUrl = 'http://192.168.11.2:8081'
        const fullUrl = `${baseUrl}${url}`

        // 获取文件名 - 截取_后面的部分
        const fileName = url.split('_').pop()
        console.log(fullUrl)

        const link = document.createElement('a')
        link.style.display = 'none'
        link.href = fullUrl
        link.setAttribute('download', fileName)
        document.body.appendChild(link)

        link.click()

        document.body.removeChild(link)
      } catch (error) {
        console.error('下载失败:', error)
        this.$message.error('下载失败，请重试')
      } finally {
        this.downloadLoading = false
      }
    },

    // 自定义上传方法
    async customUpload(options) {
      try {
        const formData = new FormData()
        formData.append('file', options.file)

        // 使用配置了拦截器的 axios 实例发送请求
        const response = await request({
          url: '/basicData/template/addTemplate',
          method: 'POST',
          data: formData,
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        })

        // 判断上传结果
        if (response.code === 1) {
          // 上传成功
          this.$message.success('文件上传成功')
          options.onSuccess(response.data)
          this.selTemplateById()
        } else {
          // 上传失败
          this.$message.error(response.msg || '文件上传失败')
          options.onError(new Error(response.msg))
        }
      } catch (error) {
        // 处理请求异常
        this.$message.error('上传失败：' + (error.message || '未知错误'))
        this.handleUploadError(error)
        options.onError(error)
      }
    }
  }
}
</script>

<style scoped>
.template-container {
  padding: 20px;
  min-height: calc(100vh - 84px);
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f0f2f5;
}

.template-card {
  width: 900px;
  padding: 30px;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.title-wrapper {
  width: 100%;
  text-align: center;
  margin-bottom: 50px;
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 20px;
}

.title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  margin: 0;
}

.upload-area {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100%;
  flex: 1;
  justify-content: center;
  min-height: 400px;
}

.upload-box {
  width: 500px;
  margin-bottom: 30px;
  text-align: center;
}

:deep(.el-upload-dragger) {
  width: 100%;
  height: 250px;
  border: 2px dashed #d9d9d9;
  border-radius: 8px;
  background-color: #fafafa;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.upload-content {
  text-align: center;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.upload-icon {
  font-size: 64px;
  color: #c0c4cc;
  margin-bottom: 20px;
}

:deep(.el-upload__text) {
  color: #606266;
  font-size: 16px;
  margin: 12px 0;
}

:deep(.el-upload__text em) {
  color: #409eff;
  font-style: normal;
  cursor: pointer;
}

.upload-tip {
  font-size: 14px;
  color: #909399;
  margin-top: 12px;
}

.file-list {
  width: 700px;
  margin: 24px 0;
}

.file-item {
  display: flex;
  align-items: center;
  padding: 12px 20px;
  background: #f5f7fa;
  border-radius: 6px;
}

.file-item .el-icon-document {
  color: #909399;
  margin-right: 12px;
  font-size: 18px;
}

.file-name {
  flex: 1;
  color: #606266;
  font-size: 14px;
}

.el-icon-circle-close {
  color: #909399;
  cursor: pointer;
  font-size: 18px;
}

.el-icon-circle-close:hover {
  color: #f56c6c;
}

.button-group {
  margin-top: 30px;
  text-align: center;
}

.button-group .el-button {
  padding: 12px 24px;
  margin: 0 12px;
  font-size: 14px;
  min-width: 100px;
}

:deep(.el-button--primary) {
  background-color: #409eff;
}

:deep(.el-button--success) {
  background-color: #67c23a;
}
</style>
